/*	
	MQ7_Example.ino

	Example sketch for MQ7 carbon monoxide detector.
		- connect analog input 
		- set A_PIN to the relevant pin
		- connect device ground to GND pin 
		- device VC to 5.0 volts

	Created by Fergus Baker
	22 August 2020
	Released into the public domain.
*/


#include "MQ7.h"
#include <WiFi.h>
#define A_PIN 2
#define VOLTAGE 5
#include <PubSubClient.h>
#include <ArduinoJson.h>


// init MQ7 device
MQ7 mq7(A_PIN, VOLTAGE);


/*配置WIFI名和密码*/
const char * WIFI_SSID     = "cnm";
const char * WIFI_PASSWORD = "123456789";

const char *mqtt_broker = "k6b11511.cn.emqx.cloud";
const char *topic = "ppm/emqx";
const char *mqtt_username = "mujiya";
const char *mqtt_password = "123456";
const int mqtt_port = 11212;

char b[50];
String c;
const char *ssid = "cnm"; // Enter your WiFi name
const char *password = "123456789";  // Enter WiFi password
String a="sdasd";
WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
    // Set software serial baud to 115200;
    Serial.begin(115200);
    // connecting to a WiFi network
    
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Connecting to WiFi..");
    }
    Serial.println("Connected to the WiFi network");
    //connecting to a mqtt broker
    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
        String client_id = "esp8266-client-";
        client_id += String(WiFi.macAddress());
        Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
            Serial.println("Public emqx mqtt broker connected");
        } else {
            Serial.print("failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }
    // publish and subscribe
    client.publish(topic, "hello emqx");
    client.subscribe(topic);
      Serial.println("");   // blank new line

  Serial.println("Calibrating MQ7");
  mq7.calibrate();    // calculates R0
  Serial.println("Calibration done!");
}

void callback(char *topic, byte *payload, unsigned int length) {
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message:");
    for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
    }
    Serial.println();
    Serial.println("-----------------------");
}

void loop() {
      MQ7 mq7(A_PIN, VOLTAGE);
    Serial.print("PPM=");
    Serial.println(mq7.readPpm());
   a=String(mq7.readPpm());
  
   sprintf(b,"{\"ppm\":%s}",a);

client.publish(topic,b);
  
    delay(1000);
}
